/**
 * @desc 公共路由
 */

import express, { Response, NextFunction } from 'express';
import multer from 'multer';
import path from 'path';
import { PORT } from '../utils/config';
import ErrorCode, { SuccessCode } from '../utils/errorCode';

// 异常code
const {
  ErrorUploadImage,
} = ErrorCode;

// 图片路径
const imgUrl = 'public/uploads';

/**
 * 生成随机文件名
 * - 时间戳（13位）+ 随机数（5位）
 */
const generateFileName = () => {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 10000);
  let filename = `${timestamp}-${random}`;
  
  // 确保文件名长度至少为20个字符
  while (filename.length < 20) {
    filename += Math.floor(Math.random() * 10);
  }
  
  return `${filename}.jpg`;
};

// 配置 multer 上传
const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, path.join(process.cwd(), imgUrl));
  },
  filename(req, file, cb) {
    cb(null, generateFileName());
  }
});

const upload = multer({ storage });
const router = express.Router();

// 图片上传接口
router.post('/upload/picture', upload.single('files'), (req: any, res: Response, next: NextFunction) => {
  try {
    // 检查文件是否存在
    if (!req.file) {
      throw new Error('No file uploaded');
    }
    
    // 从req.file中获取实际保存的文件名
    const url = `https://www.qiangwangsese.top/vote/uploads/${req.file.filename}`;
    console.log('Upload success:', url);
    
    res.json({
      url,
      ...SuccessCode
    });
  } catch (err) {
    console.error('Upload error:', err);
    res.json(ErrorUploadImage);
  }
});

export default router;